package org.shangrila.app.sys.mb;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Named;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.TabChangeEvent;
import org.primefaces.event.UnselectEvent;
import org.shangrila.app.sys.eo.SysAuthority;
import org.shangrila.app.sys.eo.SysOrganization;
import org.shangrila.app.sys.eo.SysRole;
import org.shangrila.app.sys.eo.SysUser;
import org.shangrila.app.sys.shiro.AppEncryptService;
import org.shangrila.comm.utils.MsgsUtil;
import org.shangrila.comm.dao.DbAccess;
import org.shangrila.comm.helper.IDHelper;

@Named
@SessionScoped
public class SysUserMB implements Serializable {

	private static final long serialVersionUID = 1L;

	private String userno;
	private SysUser user = new SysUser();
	
    private SysUser selectedUser;    //当前用户
	private List<SysUser> voSysUsers;

	private List<SysAuthority> voUserSysAuthorities=new ArrayList<SysAuthority>();
	private List<SysAuthority> voSysAuthorities=new ArrayList<SysAuthority>();
	
	private List<SysAuthority> selectedSysAuthorities=new ArrayList<SysAuthority>();//待设置的权限
	
	private DbAccess db = new DbAccess();
	
	public SysUserMB(){
		user = org.shangrila.app.sys.shiro.SecUtil.getCachedShiroUser();
		userno = user.getUserno();
	}
	
    public void onTabChange(TabChangeEvent event) {
    	String tabid =  event.getTab().getId();
    	//MsgsUtil.showMessages("Tab Changed", "Active Tab: " + tabid);
    	if("tab2".equals(tabid)) {
			voSysUsers = db.findEntityAll("SysUser");
			voUserSysAuthorities = user.getSysAuthorities();
			voSysAuthorities = db.findEntityAll("SysAuthority");
			//voUserSysAuthorities = ((SysUser)db.findByProperty("userno", userno, "SysUser")).getSysAuthorities();
			
			//移除已经拥有的权限
			Iterator<SysAuthority> iter = voSysAuthorities.iterator();  
			while(iter.hasNext()){
				if(voUserSysAuthorities.contains(iter.next()))
			        iter.remove();  
			} 		
    	}
    }
	
	public String cancelAction(){
		return null;
	}	
	
	public String addAction(){		
		user.setSalt(AppEncryptService.encryptSalt(user.getUserno(),user.getPassword()));
		user.setPassword(AppEncryptService.encryptPassword(user.getUserno(),user.getPassword()));
		user.setType(0);
		user.setEnabled("0");  //初始插入0，邮箱验证后为1
		user.setId(IDHelper.genNumID());
		user.setCreatedTime(new Date());
		
		//新增用户插入部门信息2
		user.setSysOrganization(new SysOrganization(2));	
		//新增用户插入角色信息10：SYS_ROLE_USER
		List<SysRole> sysRoles = new ArrayList<SysRole>();
		SysRole sysRole = new SysRole(10,"新增用户");
		sysRoles.add(sysRole);		
		user.setSysRoles(sysRoles);
		//新增用户插入权限信息901，903:SYS_ROLE_Authority
		List<SysAuthority> sysAuthorities = new ArrayList<SysAuthority>();
		SysAuthority sysAuthority1 = new SysAuthority(901,"新增用户");
		SysAuthority sysAuthority2 = new SysAuthority(903,"新增用户");
		sysAuthorities.add(sysAuthority1);
		sysAuthorities.add(sysAuthority2);
		user.setSysAuthorities(sysAuthorities);
		
		db.beginTransaction();
		db.insert(user);
		db.commitTransaction();		
		
		MsgsUtil.showMessages("新增用户", "新增用户成功。");
		return null;
	}

	public String authAction(){
		
		voUserSysAuthorities.addAll(selectedSysAuthorities);//把新的权限添加到已有权限列表
		selectedUser.setSysAuthorities(voUserSysAuthorities);
		db.beginTransaction();
		db.update(selectedUser);
		db.commitTransaction();	
		
		MsgsUtil.showMessages("授权", "授予选定权限成功。");
		return null;
	}
	
    public void onAuthRowSelect(SelectEvent event) {
    	MsgsUtil.showMessages("Authority Selected", ((SysAuthority) event.getObject()).getName());
     }
 
    public void onAuthRowUnselect(UnselectEvent event) {
    	MsgsUtil.showMessages("Authority Unselected", ((SysAuthority) event.getObject()).getName());
    }

    public void onUserRowSelect(SelectEvent event) {
    	//MsgsUtil.showMessages("Authority Selected", ((SysUser) event.getObject()).getUsername());
    	selectedUser = (SysUser) event.getObject();
    	userno = selectedUser.getUserno();
    	
		voUserSysAuthorities = selectedUser.getSysAuthorities();
		voSysAuthorities = db.findEntityAll("SysAuthority");
		//voUserSysAuthorities = ((SysUser)db.findByProperty("userno", userno, "SysUser")).getSysAuthorities();
		
		//移除已经拥有的权限
		Iterator<SysAuthority> iter = voSysAuthorities.iterator();  
		while(iter.hasNext()){
			if(voUserSysAuthorities.contains(iter.next()))
		        iter.remove();  
		}
    	
     }
 
    public void onUserRowUnselect(UnselectEvent event) {
    	MsgsUtil.showMessages("Authority Unselected", ((SysUser) event.getObject()).getUsername());
    }

	public void validateUsername(FacesContext arg0, UIComponent arg1,
			Object arg3) throws ValidatorException {
		String content = (String) arg3;

		String regExp = "^[A-Za-z0-9]{3,16}$";
		if (!content.matches(regExp)) {
			throw new ValidatorException(MsgsUtil.showMessages("info",
					"请输入合法字符"));
		}
	}
	
	public void validatePassword(FacesContext arg0, UIComponent arg1,
			Object arg3) throws ValidatorException {

		String content = (String) arg3;

		// 判断字符串的内容:字母数字下划线以及特殊字符(~`!@#$%^&*()+-_=|:;/'\"<>,.?)组合,3-36个字符。
		// 考虑SQL注入风险，不能使用' " = | + - <> []
		String regExp = "^[A-Za-z0-9~`!@#$%^&*()_<>/\\{}:;,.?]{3,20}$";
		// String regExp = "^[A-Za-z0-9]{3,16}$";
		if (!content.matches(regExp)) {
			throw new ValidatorException(MsgsUtil.showMessages("info",
					"请输入合法字符"));
		}
	}
	
	public SysUser getUser() {
		return user;
	}

	public void setUser(SysUser user) {
		this.user = user;
	}
	public SysUser getSelectedUser() {
		return selectedUser;
	}

	public void setSelectedUser(SysUser selectedUser) {
		this.selectedUser = selectedUser;
	}

	public List<SysUser> getVoSysUsers() {
		return voSysUsers;
	}

	public void setVoSysUsers(List<SysUser> voSysUsers) {
		this.voSysUsers = voSysUsers;
	}

	public List<SysAuthority> getVoSysAuthorities() {
		return voSysAuthorities;
	}

	public void setVoSysAuthorities(List<SysAuthority> voSysAuthorities) {
		this.voSysAuthorities = voSysAuthorities;
	}

	public List<SysAuthority> getSelectedSysAuthorities() {
		return selectedSysAuthorities;
	}

	public void setSelectedSysAuthorities(List<SysAuthority> selectedSysAuthorities) {
		this.selectedSysAuthorities = selectedSysAuthorities;
	}


	public String getUserno() {
		return userno;
	}


	public void setUserno(String userno) {
		this.userno = userno;
	}


	public List<SysAuthority> getVoUserSysAuthorities() {
		return voUserSysAuthorities;
	}


	public void setVoUserSysAuthorities(List<SysAuthority> voUserSysAuthorities) {
		this.voUserSysAuthorities = voUserSysAuthorities;
	}
   
}